// 修复包声明重复问题
package type.fragment.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import type.fragment.SecondLevelCategory;
import type.fragment.ThirdLevelCategory;
import com.example.xfengshopping.R;

public class SubcategoryRecyclerAdapter extends RecyclerView.Adapter<SubcategoryRecyclerAdapter.ViewHolder> {
    private Context context;
    private List<SecondLevelCategory> secondLevelCategoryList;
    private OnThirdLevelClickListener listener;

    public SubcategoryRecyclerAdapter(Context context, List<SecondLevelCategory> list) {
        this.context = context;
        this.secondLevelCategoryList = new ArrayList<>(list);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_subcategory_group, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        SecondLevelCategory secondCategory = secondLevelCategoryList.get(position);
        holder.tvSecondCategory.setText(secondCategory.getCategoryName());

        // 设置GridLayoutManager实现一行3个
        GridLayoutManager layoutManager = new GridLayoutManager(context, 3);
        holder.rvThirdCategory.setLayoutManager(layoutManager);

        ThirdLevelAdapter thirdAdapter = new ThirdLevelAdapter(context, secondCategory.getThirdLevelCategoryVOS());
        thirdAdapter.setOnItemClickListener(category -> {
            if (listener != null) {
                listener.onThirdLevelClick(category);
            }
        });
        holder.rvThirdCategory.setAdapter(thirdAdapter);
    }

    @Override
    public int getItemCount() {
        return secondLevelCategoryList.size();
    }

    public void updateData(List<SecondLevelCategory> newData) {
        secondLevelCategoryList.clear();
        secondLevelCategoryList.addAll(newData);
        notifyDataSetChanged();
    }

    public interface OnThirdLevelClickListener {
        void onThirdLevelClick(ThirdLevelCategory category);
    }

    public void setOnThirdLevelClickListener(OnThirdLevelClickListener listener) {
        this.listener = listener;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvSecondCategory;
        RecyclerView rvThirdCategory;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvSecondCategory = itemView.findViewById(R.id.tv_second_category);
            rvThirdCategory = itemView.findViewById(R.id.rv_third_category);
        }
    }
}